package shop.ynubeggar.interceptor;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import shop.ynubeggar.exception.CustomException;
import shop.ynubeggar.model.valueobject.LoginUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static shop.ynubeggar.utils.JwtParameter.KEY;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("Authorization");
        if (accessToken == null) {
            accessToken = request.getHeader("token");
        }
        if (accessToken.isBlank()) {
            throw new CustomException(HttpStatus.UNAUTHORIZED, "unauthorized");
        }
        if (!JWTUtil.verify(accessToken, KEY.getBytes())) {
            throw new CustomException(HttpStatus.UNAUTHORIZED, "authorization expired");
        }
        final JWT jwt = JWTUtil.parseToken(accessToken);
//        lombok 的 builder 模式
        LoginUser loginUser = LoginUser.builder()
                .id(Long.valueOf(jwt.getPayload("id").toString()))
                .name((String) jwt.getPayload("name"))
                .mail((String) jwt.getPayload("mail"))
                .phone((String) jwt.getPayload("phone"))
                .userType(Integer.valueOf(jwt.getPayload("userType").toString()))
                .build();
        threadLocal.set(loginUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
